<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'

const tags = ref([
  { title: '全部评价', tagCount: 832 },
  { title: '有图', tagCount: 46 }
])

const getE = async () => {
  const res = await axios.get('https://mock.boxuegu.com/mock/1175/goods/4001231/evaluate')
  purchaseCount.value = res.data.result.salesCount
  rating.value = `${res.data.result.praisePercent}`
  tags.value = [...tags.value, ...res.data.result.tags]
}
getE()

const displayedComments = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const showModal = ref(false)
const modalIndex = ref(0)
const rating = ref('')
const purchaseCount = ref(0)
const totalComments = ref(0)
const selectedTag = ref(tags.value[0])
const selectedSort = ref('default')

const sortOptions = [
  { value: 'default', label: '默认' },
  { value: 'latest', label: '最新' },
  { value: 'hottest', label: '最热' }
]

const fetchComments = async (page, tag, sort) => {
  try {
    let fetchedComments = []
    let hasMoreComments = true
    let currentPage = page

    while (fetchedComments.length < pageSize.value && hasMoreComments) {
      const params = {
        page: currentPage,
        pageSize: pageSize.value,
        ...(tag === '有图' ? { hasPicture: true } : tag !== '全部评价' && { tag }),
        ...(sort !== 'default' && {
          sortField: sort === 'latest' ? 'createTime' : sort === 'hottest' ? 'praiseCount' : sort
        })
      }
      const res = await axios.get(
        'https://mock.boxuegu.com/mock/1175/goods/4001231/evaluate/page',
        {
          params
        }
      )
      const comments = res.data.result.items
      totalComments.value = res.data.result.counts
      currentPage++

      if (comments.length > 0) {
        if (tag === '有图') {
          fetchedComments = [
            ...fetchedComments,
            ...comments.filter(comment => comment.pictures && comment.pictures.length > 0)
          ]
        } else {
          fetchedComments = [...fetchedComments, ...comments]
        }
      } else {
        hasMoreComments = false
      }
    }

    displayedComments.value = fetchedComments.slice(0, pageSize.value)
    currentPage.value = page
  } catch (error) {
    console.error('Error fetching comments:', error)
  }
}

const handleCurrentChange = page => {
  currentPage.value = page
  fetchComments(page, selectedTag.value.title, selectedSort.value)
}

const selectTag = tag => {
  selectedTag.value = tag
  currentPage.value = 1
  fetchComments(currentPage.value, tag.title, selectedSort.value)
}

const selectSort = sortType => {
  selectedSort.value = sortType
  currentPage.value = 1
  fetchComments(currentPage.value, selectedTag.value.title, sortType)
}

const showImage = index => {
  modalIndex.value = index
  showModal.value = true
}

const closeModal = () => {
  showModal.value = false
}

onMounted(() => {
  fetchComments(currentPage.value, selectedTag.value.title, selectedSort.value)
})
</script>

<template>
  <div>
    <div class="top-bar">
      <div class="purchase-and-rating">
        <div class="purchase-count">
          <span style="font-size: 30px; color: rgb(207, 68, 68)">{{ purchaseCount }}</span>
          <span style="font-size: 15px; color: grey">人购买</span>
        </div>
        <div class="rating">
          <span style="font-size: 30px; color: rgb(207, 68, 68)">{{ rating }}</span>
          <span style="font-size: 15px; color: grey">好评率</span>
        </div>
      </div>
      <span style="margin-right: 10px">大家都在说：</span>
      <div class="tags-bar">
        <el-button
          v-for="(tag, index) in tags"
          :key="index"
          size="large"
          type="primary"
          plain
          :class="{ active: tag === selectedTag }"
          @click="selectTag(tag)"
        >
          {{ tag.title }} ({{ tag.tagCount }})
        </el-button>
      </div>
    </div>
    <el-card>
      <div class="sort-options">
        排序：

        <div
          v-for="(option, index) in sortOptions"
          :key="index"
          :class="{ sortactive: selectedSort === option.value }"
          @click="() => selectSort(option.value)"
        >
          {{ option.label }}
        </div>
      </div>
    </el-card>

    <div v-for="comment in displayedComments" :key="comment" class="commentcard">
      <el-card class="commentcontainer">
        <div class="userinfo-container">
          <div style="text-align: center">
            <el-avatar :src="comment.member.avatar" />{{ comment.member.nickname }}
          </div>
        </div>
        <div class="commentdetails">
          <span class="scoreandspecs">
            <el-rate v-model="comment.score" disabled text-color="#ff9900" class="rate-item" />
            <p
              v-for="(commentspec, index) in comment.orderInfo.specs"
              :key="index"
              class="spec-item"
            >
              {{ commentspec.name }}:{{ commentspec.nameValue }}
            </p>
          </span>
          <div class="commentcontent">{{ comment.content }}</div>
          <div>
            <div style="display: flex; flex-wrap: wrap">
              <div
                v-for="(picture, index) in comment.pictures"
                :key="index"
                class="thumbnail-container"
              >
                <img :src="picture" alt="" class="thumbnail" @click="showImage(index)" />
              </div>
            </div>

            <div v-if="showModal" class="modal" @click="closeModal">
              <img :src="comment.pictures[modalIndex]" alt="" class="modal-content" />
            </div>
          </div>

          <div class="commentfooter">
            <div class="commenttime">{{ comment.createTime }}</div>
            <div class="likes">
              <span>{{ comment.praiseCount }}</span>
              <el-icon>
                <StarFilled />
              </el-icon>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    <div style="display: flex; justify-content: center">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="totalComments"
        hide-on-single-page
        layout="prev, pager, next"
      ></el-pagination>
    </div>
  </div>
</template>

<style scoped lang="scss">
.commentcontainer {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.userinfo-container {
  display: flex;
  align-items: center;
  gap: 5px;
  justify-content: flex-start;
}

.avatar {
  height: 32px;
  width: 32px;
}

.nickname {
  margin-right: auto;
}

.commentdetails {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  gap: 5px;
}

.scoreandspecs {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  min-width: 250px;
}

.rate-item {
  font-size: 14px;
  color: #ff9900;
}

.spec-item {
  margin-right: 10px;
  font-size: 12px;
  color: #999;
}

.commentcontent {
  font-size: 14px;
  color: #666;

  flex: 1;
  word-break: break-word;
  height: 10%;
}

.commenttime {
  font-size: 12px;
  color: #999;
}

.likes {
  display: flex;
  align-items: center;
}

.likes span {
  margin-right: 5px;
}

.active {
  background-color: rgb(39, 186, 155) !important;
  color: white !important;
}

.sortactive {
  color: rgb(39, 186, 155);
}

.top-bar {
  display: flex;
  width: 100%;
  height: 100px;
  margin-bottom: 10px;
  flex-wrap: wrap;
}

.purchase-and-rating {
  flex: 1;
  display: flex;
  width: 40%;
}

.purchase-count,
.rating {
  width: 50%;
}

.purchase-count span,
.rating span {
  display: block;
}

.tags-bar {
  flex: 2;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  gap: 10px;
}

.el-button {
  background-color: rgb(245, 245, 245);
  border-color: grey;
  color: grey;
  flex: 0 0 calc(30% - 10px);
  margin-left: 0;
  margin-right: 10px;
}

.modal {
  /*  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  z-index: 999; */
}

.modal-content {
  /*   max-width: 90%;
  max-height: 90%;
  object-fit: contain; */
}

.commentfooter {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  min-width: 250px;
}

.sort-options {
  display: flex;
  justify-content: space-around;
}

.sort-options div {
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.thumbnail-container {
  width: 19%;
  margin-bottom: 10px;
  margin-right: 5px;
  position: relative;
  border: 1px solid #ccc;
  height: 200px;
}

.thumbnail {
  width: 100%;
  height: 200px;
  object-fit: contain;
  cursor: pointer;
}
</style>
